﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using System.IO;

namespace FileDeleteNew
{
    class JsonStore
    {
        private string storePath;
        public string StorePath
        {
            get { return storePath; }
            set { storePath = value; }
        }

        public bool StoreJosn(object data)
        {
            bool res = true;
            string json = JsonConvert.SerializeObject(data, Formatting.Indented);
            try
            {
                File.WriteAllText(storePath, json, Encoding.UTF8);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                res = false;

            }
            return res;
        }

        public List<T> ReadJson<T>()
        {
            if (File.Exists(storePath))
            {
                string jsonStr = File.ReadAllText(storePath);
                List<FileClass> deserializedPeople = JsonConvert.DeserializeObject<List<FileClass>>(jsonStr);
                var list = new List<T>(JsonConvert.DeserializeObject<List<T>>(jsonStr));
                return list;
            }
            return null;
        }

        /// <summary>
        /// 添加进JSON文件
        /// </summary>
        /// <param name="newItem"></param>
        public void AddAndStore(FileClass newItem)
        {
            List<FileClass> existingItems = new List<FileClass>();

            // 尝试读取现有的JSON文件
            if (File.Exists(StorePath))
            {
                string jsonStr = File.ReadAllText(StorePath);
                existingItems = JsonConvert.DeserializeObject<List<FileClass>>(jsonStr);
            }

            // 将新项添加到列表中
            existingItems.Add(newItem);

            // 将更新后的列表序列化为JSON并写回到文件
            string jsonToStore = JsonConvert.SerializeObject(existingItems, Formatting.Indented);
            File.WriteAllText(StorePath, jsonToStore);
        }
    }
}
